package com.k2data.k2app.util;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 时间工具类
 * Created by clb on 17-5-23.
 */
public class DateFormatterUtil {
	public static final String timePattern = "yyyy-MM-dd HH:mm:ss";
	private static final String minPattern = "yyyy-MM-dd HH:mm";
	private static final String timePattern1 = "yyyyMMddHHmmss";
	public static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(timePattern);
	public static final DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern(timePattern1);
	public static final DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern(minPattern);
	public static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timePattern);

	public static String getNow(DateTimeFormatter dateTimeFormatter){
		LocalDateTime localDateTime = LocalDateTime.now();
		return localDateTime.format(dateTimeFormatter);
	}

	public static String getNow(){
		LocalDateTime localDateTime = LocalDateTime.now();
		return localDateTime.format(dateTimeFormatter);
	}

	public static String parseToString(LocalDateTime localDateTime,DateTimeFormatter dateTimeFormatter){
		return localDateTime.format(dateTimeFormatter);
	}

	public static String parseToString(LocalDateTime localDateTime){
		return localDateTime.format(dateTimeFormatter);
	}


	/**
	 * 字符串转换为localDataTime
	 * @param type
	 * @param value
	 * @param <T>
	 * @return
	 * @throws Throwable
	 */
	public static <T> T convertToType(Class<T> type, Object value){
		if(value == null){
			return null;
		}
		if (LocalDateTime.class.equals(type)) {
			return type.cast(LocalDateTime.parse(value.toString(), dateTimeFormatter));
		}
		return null;
	}

	public static LocalDateTime UDateToLocalDateTime(Date date) {
		Instant instant = date.toInstant();
		ZoneId zone = ZoneId.systemDefault();
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
		return localDateTime;
	}
}
